package com.qf.kele02.filter;

import com.qf.kele02.dao.UserDao;
import com.qf.kele02.entity.User;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * @Author: 可乐
 * @Description:
 * @CreateTime: 2022-10-19  18:50
 */

public class MyFilter implements Filter {
	@Autowired
	UserDao userDao;
	private String name;

	public String getName( ) {
		return name;
	}

	public void setName( String name ) {
		this.name=name;
	}

	@Override
	public void init( FilterConfig filterConfig ) throws ServletException {
		System.out.println( "DemoFilter init" );
		System.out.println( name );
	}

	@Override
	public void doFilter( ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain ) throws IOException, ServletException {
		HttpServletResponse response=(HttpServletResponse) servletResponse;
		HttpServletRequest request=(HttpServletRequest) servletRequest;
		request.setCharacterEncoding( "UTF-8" );
		response.setContentType( "text/html;charset=utf-8" );

		//自动登录
		Cookie[] cookies=request.getCookies( );

		for(Cookie cookie: cookies) {
			if("usertoken".equals( cookie.getName( ) )) {

				//调用Dao层来查询有没有这个用户
				String[] split=cookie.getName( ).split( "-" );

				User userByName=userDao.getUserByName( split[0] );

				if(userByName!=null) {
					HttpSession session=request.getSession( );
					session.setAttribute( "user",userByName );
					response.sendRedirect( "plateform.html" );
				}else {
					response.sendRedirect( "login.html" );
				}

			}
		}

	}
}
